'use strict';
const db = uniCloud.database()
const coursesCollection = db.collection('courses')

exports.main = async (event, context) => {
	const { courseInfo } = event
	
	try {
		// 数据验证
		if (!courseInfo.title) {
			return {
				code: -1,
				msg: '课程标题不能为空'
			}
		}
		
		if (!courseInfo.imageUrl) {
			return {
				code: -1,
				msg: '课程封面不能为空'
			}
		}
		
		// 添加创建时间
		courseInfo.createTime = Date.now()
		
		// 添加课程
		const res = await coursesCollection.add(courseInfo)
		
		return {
			code: 0,
			msg: '添加成功',
			data: {
				_id: res.id
			}
		}
	} catch (e) {
		console.error('添加课程失败', e)
		return {
			code: -1,
			msg: '添加失败',
			error: e
		}
	}
} 